from novel.dao import POOL


def updata(item):
    """
    更新章节
    :return:
    """
    conn = POOL.connection()
    cursor = conn.cursor()

    charpter_sql = """
              UPDATE `bookdb`.`novel_info` SET `chapter_name` = %s, `chapter_content` = %s WHERE `chapter_url` = %s
         """
    cursor.execute(charpter_sql, (item['title'], item['text'], item['source']))
    conn.commit()
    cursor.close()
    conn.close()


def insertCharpter(item):
    """
    插入章节
    :param item:
    :return:
    """
    sql= """
         INSERT INTO `bookdb`.`novel_info` 
                (`novel_id`, `chapter_no`, `chapter_name`, `chapter_content`, `chapter_url`)
        VALUES (%s,%s, %s, %s, %s)
        """
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute(sql, (item['id'], item['no'], item['title'],item['text'],item['source']))
    conn.commit()
    cursor.close()
    conn.close()

def findById(id):
    """
    通过主键查询章节
    :param id:
    :return:
    """
    sql= """
         SELECT * FROM `bookdb`.`novel_info`  WHERE novel_info.id = %s
        """
    conn = POOL.connection()
    cursor = conn.cursor()
    cursor.execute(sql, (id))
    data = cursor.fetchone()
    cursor.close()
    conn.close()
    return data


def insertmany(id,charpters):
    # 插入小说章节
    chapter_sql = """
                  INSERT INTO `bookdb`.`novel_info`(`novel_id`,`chapter_name`,`chapter_no`, `chapter_url`) VALUES (%s,%s,%s, %s)
              """
    conn = POOL.connection()
    cursor = conn.cursor()
    param = []
    for idx, c in enumerate(charpters):
        param.append([id, c['title'],c['no'], c['linke']])
    if len(param) != 0:
        cursor.executemany(chapter_sql, param)
        conn.commit()
    cursor.close()
    conn.close()


if __name__ == '__main__':

    itemmap={
        "title":"123",
        "text":"123",
        "source":"123",
    }
    updata(itemmap)